package cn.db101.kaoqinserver.controller;

import cn.db101.kaoqinserver.config.ApiResult;
import cn.db101.kaoqinserver.domain.User;
import cn.db101.kaoqinserver.enumration.UserType;
import cn.db101.kaoqinserver.model.request.LoginRequest;
import cn.db101.kaoqinserver.model.response.LoginResponse;
import cn.db101.kaoqinserver.service.UserService;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.SecureUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("v1/kaoqin/login")
public class LoginController {

    @Autowired
    private UserService userService;

    @PostMapping
    public ApiResult login(@RequestBody LoginRequest request) {


        User user = userService.getUserByLoginName(request.getLoginName());

        if(user == null) {
            return ApiResult.ofError(HttpStatus.BAD_REQUEST.value(), "账户密码错误");
        }

        if(user.getUserType() == UserType.TEACHER.getValue() ||
                user.getUserType() == UserType.ADMIN.getValue()) {

            // 验证码校验
            String captcha = userService.getCaptcha(request.getCaptchaId());

            if (!captcha.equals(request.getVerifyCode())) {
                userService.removeCaptcha(request.getCaptchaId());
                return ApiResult.ofError(HttpStatus.BAD_REQUEST.value(), "验证码错误");
            }

            userService.removeCaptcha(request.getCaptchaId());
        }

        String md5 = SecureUtil.md5(request.getLoginPwd());

        // 验证密码是否正确
        if (md5.equals(user.getLoginPwd())) {
            LoginResponse loginResponse = new LoginResponse();
            user.setLoginPwd(null);
            loginResponse.setUser(user);
            StpUtil.login(user.getId());
            loginResponse.setToken(StpUtil.getTokenValue());
            return ApiResult.ofSuccess(loginResponse);
        } else {
            return ApiResult.ofError(HttpStatus.BAD_REQUEST.value(), "密码错误");
        }
    }

}